package com.example.aiinterview.config;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.servlet.NoHandlerFoundException;

import jakarta.servlet.http.HttpServletRequest;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public RedirectView handleException(Exception ex, HttpServletRequest request, RedirectAttributes redirectAttributes) {
        String requestURI = request.getRequestURI();

        // 忽略浏览器自动发起的特定请求
        if (requestURI.contains(".well-known/appspecific")) {
            // 不记录这类请求的错误日志
            return null; // 或者返回一个空的视图
        }

        // 记录其他错误
        System.err.println("Global exception handler caught: " + ex.getMessage());
        ex.printStackTrace();

        // 根据请求路径决定重定向位置
        if (requestURI.contains("/chat-interview/")) {
            redirectAttributes.addFlashAttribute("errorMessage", "加载面试页面时发生错误：" + ex.getMessage());
            return new RedirectView("/interview");
        } else if (requestURI.contains("/api/")) {
            // API请求的错误处理
            redirectAttributes.addFlashAttribute("errorMessage", "请求处理失败：" + ex.getMessage());
            return new RedirectView("/interview");
        } else {
            redirectAttributes.addFlashAttribute("errorMessage", "系统错误：" + ex.getMessage());
            return new RedirectView("/interview");
        }
    }

    // 专门处理 404 错误
    @ExceptionHandler(NoHandlerFoundException.class)
    public RedirectView handleNotFound(NoHandlerFoundException ex, HttpServletRequest request, RedirectAttributes redirectAttributes) {
        String requestURI = request.getRequestURI();

        // 忽略浏览器自动发起的特定请求
        if (requestURI.contains(".well-known/appspecific")) {
            return null;
        }

        // 对于其他 404 错误，可以记录日志但不显示给用户
        System.out.println("404 Not Found: " + requestURI);
        return new RedirectView("/interview");
    }
}
